package com.dong.order.service;

import com.dong.basic.constant.Constant;
import com.dong.basic.enums.OrderStatusEnum;
import com.dong.basic.tools.ConnectionTools;
import com.dong.order.dao.OrderDetailDao;
import com.dong.basic.dto.OrderMessageDTO;

import com.dong.basic.po.OrderDetailPO;
import com.dong.order.vo.OrderCreateVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;

/**
 * 处理关于订单的业务请求
 */
@Service
@Slf4j
public class OrderService {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private OrderMessageOrderService orderMessageService;
    @Autowired
    private Channel channel;


    public OrderDetailPO createOrder(OrderCreateVO vo) {
        OrderDetailPO po = new OrderDetailPO();
        po.setAddress(vo.getAddress());
        po.setAccountId(vo.getAccountId());
        po.setProductId(vo.getProductId());
        po.setStatus(OrderStatusEnum.ORDER_CREATING);
        po.setDate(new Date());
        orderDetailDao.insert(po);
        log.info("数据插入成功!");

        OrderMessageDTO orderMessageDTO = OrderMessageDTO.createFromPo4Creating(po);
        try {
            String msg = objectMapper.writeValueAsString(orderMessageDTO);

            channel.basicPublish(Constant.Exchange.RESTAURANT,Constant.RoutingKey.RESTAURANT,true,null,msg.getBytes());
            if(!channel.waitForConfirms()) {
                log.error("完了, 消息没被发送过去!");
            };

            log.info("订单创建消息发送成功");

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return po;
    }
}
